package de.preamp.clients.java.lib;

import java.io.IOException;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.event.ChangeEvent;

import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.preamp.clients.java.data.Album;
import de.preamp.clients.java.data.Artist;
import de.preamp.clients.java.data.Track;
import de.preamp.clients.java.net.ServerConnectionImpl;

/**
 * A class managing the media-library using the preamp server and local cache.
 * 
 * @author André Stannek
 * @since 2010-03-23
 * @version 2011-06-11
 */
@Component("searchLibrary")
public class SearchLibrary extends AbstractLibrary
{
    /**
     * Generated UID.
     */
    private static final long serialVersionUID = -2305669336723124086L;

    /**
     */
    private transient SortedSet<Track> tracks;

    /**
     * 
     */
    @Autowired(required = true)
    private ServerConnectionImpl serverConnection;

    /**
     * @param search
     *            the keyword
     * @throws JSONException
     *             if library couldn't be created because the server returned
     *             broken results.
     * @throws IOException
     *             if library couldn't be created because the server connection
     *             was impossible.
     */
    public final void search(final String search) throws JSONException,
	    IOException
    {
	tracks = new TreeSet<Track>(serverConnection.getFiles(search));
	final SortedSet<Album> albums = new TreeSet<Album>();
	final SortedSet<Artist> artists = new TreeSet<Artist>();

	for (final Track track : tracks)
	{
	    albums.add(new Album(track.getAlbum(), track.getCover()));
	    artists.add(new Artist(track.getArtist()));
	}
	for (final Album album : albums)
	{
	    for (final Track track : tracks)
	    {
		album.addTrack(track);
	    }
	}
	for (final Artist artist : artists)
	{
	    artist.addChangeListener(this);
	    add(size(), artist);
	    for (final Album album : albums)
	    {
		final SortedSet<Track> albumTracks = album.getTracks();
		if (new Artist(albumTracks.first().getArtist()).equals(artist))
		{
		    album.addChangeListener(this);
		    add(size(), album);
		    for (final Track track : albumTracks)
		    {
			track.addChangeListener(this);
			add(size(), track);
		    }
		}
	    }
	}
    }

    @Override
    public final void stateChanged(final ChangeEvent event)
    {
	final int index = this.indexOf(event.getSource());
	fireContentsChanged(this, index, index + 1);
    }

    @Override
    public void update() throws JSONException, IOException
    {
	// TODO Auto-generated method stub

    }
}
